package com.up.interview.redis.redisson;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: liuchengjun
 * @title: JvmLockImpl
 * @projectName: 海联技术中台V2.0
 * @depart 软件事业部
 * @description:
 * @date: 2025/10/20/周一 15:54 (星期一)
 * @since V2.0
 */


@Component("jvmLock")
public class JvmLockImpl implements DistributedLock{
    private static final Logger logger = LoggerFactory.getLogger(JvmLockImpl.class);
    private final ConcurrentHashMap<String, ReentrantLock> lockMap = new ConcurrentHashMap<>();

    private ReentrantLock getLock(String lockKey) {
        return lockMap.computeIfAbsent(lockKey, k -> new ReentrantLock());
    }

    @Override
    public void lock(String lockKey) {
        ReentrantLock lock = getLock(lockKey);
        lock.lock();
        logger.debug("JVM锁加锁成功: {}", lockKey);
    }

    @Override
    public boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
        ReentrantLock lock = getLock(lockKey);
        boolean acquired = lock.tryLock(waitTime, unit);
        if (acquired) {
            logger.debug("JVM锁尝试加锁成功: {}", lockKey);
        } else {
            logger.debug("JVM锁尝试加锁失败: {}", lockKey);
        }
        return acquired;
    }

    @Override
    public void unlock(String lockKey) {
        ReentrantLock lock = getLock(lockKey);
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
            lockMap.remove(lockKey);//帮助回收
            logger.debug("JVM锁解锁成功: {}", lockKey);
        }
    }
}
